package com.wxd.action;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.sun.org.apache.xml.internal.serializer.ElemDesc;
import com.wxd.bean.UserInfo;
import com.wxd.service.LoginService;
import com.wxd.service.impl.LoginServiceImpl;
import com.wxd.util.OutPut;

public class LoginAction extends ActionSupport {
	private LoginService loginService = new LoginServiceImpl();

	public String execute() {
		HttpServletRequest req = ServletActionContext.getRequest();
		HttpSession session = req.getSession();
		Object userInfo = session.getAttribute("userInfo");

		if (userInfo != null) {
			return SUCCESS;
		} else {
			return LOGIN;
		}
	}

	public void userLogin() {
		JSONObject result = new JSONObject();
		result.put("success", new Boolean(false));
		HttpServletRequest req = ServletActionContext.getRequest();
		HttpSession session = req.getSession();
		String userName = req.getParameter("userName");
		String userPwd = req.getParameter("userPwd");
		
		String errMsg = "";
		
		// 如果用户名为空则检查session里面是否已经登录了
		if ((userName == null || "".equals(userName))
				&& (userPwd == null || "".equals(userPwd))) {
			errMsg = "请填写用户名和密码";
			result.put("errtype", "3");

		} else if (userPwd == null || "".equals(userPwd)) {
			errMsg = "请填写用户密码";
			result.put("errtype", "2");
		} else if (userName == null || "".equals(userName)) {
			errMsg = "请填写用户名";
			result.put("errtype", "1");

		} else {
			session.removeAttribute("userInfo");
			// 然后核对用户名密码是否正确并跳转到相应的页面

			UserInfo userInfo = loginService.getUserInfo(userName, userPwd);
			if (userInfo == null) {
				errMsg = "用户名或密码错误";
				result.put("errtype", "2");
			} else {
				result.put("success",new Boolean(true));
				session.setAttribute("userInfo", userInfo);
				result.put("userid", userInfo.getId());
			}
		}
		HttpServletResponse response = ServletActionContext.getResponse();
		
//		try {
//			result.put("msg", new String(errMsg.getBytes("utf-8"),"8859_1"));
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
		result.put("msg", errMsg);
		
		OutPut.responseWrite(response, result.toString());
	}

	// 打开登录页面
	public String loginPage() {
		return SUCCESS;
	}

	// 退出
	public String logout() {
		HttpServletRequest req = ServletActionContext.getRequest();
		HttpSession session = req.getSession();
		session.removeAttribute("userInfo");
		return SUCCESS;
	}
}
